
#include "./medianFilter2D.h"

#include <algorithm>
#include <stdexcept>

using std::invalid_argument;
using std::max;
using std::min;
using std::sort;

/**
 * @brief 二维中值滤波实现​。
 * 适用于图像处理（如去除椒盐噪声）：
 *
 * @param input
 * @param windowSize
 * @return vector<vector<double>>
 */
vector<vector<double>> medianFilter2D(const vector<vector<double>>& input, int windowSize)
{
    if (windowSize <= 0) {
        throw invalid_argument("窗口大小必须为正整数");
    }
    if (windowSize % 2 == 0) {
        throw invalid_argument("窗口大小必须为奇数"); // 保证对称性
    }

    int half = windowSize / 2;
    auto rows = (int)input.size();
    if (rows == 0) {
        return {};
    }
    auto cols = (int)input[0].size();

    vector<vector<double>> output(rows, vector<double>(cols));

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            vector<double> window;

            // 提取窗口内的所有元素（处理边缘）
            for (int x = max(0, i - half); x <= min(rows - 1, i + half); ++x) {
                for (int y = max(0, j - half); y <= min(cols - 1, j + half); ++y) {
                    window.push_back(input[x][y]);
                }
            }

            // 排序并取中值
            sort(window.begin(), window.end());
            output[i][j] = window[window.size() / 2];
        }
    }

    return output;
}
